#include "TcpServer.hpp"
#include <memory>
#include "Protocol.hpp"
#include "Calculator.hpp"
#include "Deamon.hpp"

using namespace LogModule;

using cal_fun = std::function<Response(const Request &req)>;

class Parse
{
public:
    Parse(cal_fun c) : _cal(c)
    {}
    std::string Entry(std::string &package)
    {
        // 1. 判断报文的完整性
        std::string message;
        std::string respstr;
        
        // std::cout << "进入Entry的逻辑："<<std::endl;
        // std::cout << "package："<< package <<std::endl;


        while(Decode(package, &message))
        {
            LOG(LogLevel::DEBUG) << "Content: \n" << message;
            if(message.empty())
                break;

            // 2. 进行反序列化，message是一个曾经被序列化的request
            Request req;
            if(!req.Deserialize(message))
                break;

            std::cout << "##########" << std::endl; 
            req.Print();
            std::cout << "##########" << std::endl; 

            // 3. 计算
            Response resp = _cal(req);

            // 4. 序列化
            std::string res;
            resp.Serialize(res);
            LOG(LogLevel::DEBUG) << "序列化: \n" << res;

            // 5. 添加长度报头字段！
            Encode(res);
            LOG(LogLevel::DEBUG) << "Encode: \n" <<  res;

            // 6. 拼接应答
            respstr += res;
        }
        LOG(LogLevel::DEBUG) << "respstr: \n" << respstr;

        return respstr;
    }

private:
    cal_fun _cal;
};

int main()
{
    ENABLE_FILE_LOG();
    //ENABLE_CONSOLE_LOG();


    //1. 创建计算模块
    Calculator mycall;

    //2. 解析对象
    Parse myparse([&mycall](const Request &req){
        return mycall.Excute(req);
    });

    //3.  建立通信模块 -- 只负责IO。
    std::unique_ptr<TcpServer> tsvr = std::make_unique<TcpServer>([&myparse](std::string &package){
        return myparse.Entry(package);        
    });

    //std::unique_ptr<TcpServer> tsvr = std::make_unique<TcpServer>();

    tsvr->InitServer();
    tsvr->Start();

    return 0;
}

